package com.wanghua.mall.cart.interceptor;

import com.wanghua.common.vo.UserResponseVo;
import com.wanghua.mall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.UUID;

/**
 * @author wanghua
 * @create 2021-09-07 8:37
 * 拦截器
 * 在执行目标方法前,先判断用户登录状态。并封装用户信息传递给Controller
 */
public class CartInterceptor implements HandlerInterceptor {
    //ThreadLocal同一线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession httpSession = request.getSession();
        UserResponseVo loginUser = (UserResponseVo) httpSession.getAttribute("loginUser");
        if (loginUser != null) {
            userInfoTo.setUserId(loginUser.getId());
        } else {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0)
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("user-key")) {
                        System.out.println(cookie);
                        userInfoTo.setUserKey(cookie.getValue());
                    }
                }
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后，分配临时用户
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //设置cookie
        UserInfoTo userInfoTo = threadLocal.get();
        if (!StringUtils.hasLength(userInfoTo.getUserKey())) {//说明第一次访问，需要设置cookie
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
            Cookie cookie = new Cookie("user-key", userInfoTo.getUserKey());
            cookie.setDomain("mall.com");
            cookie.setMaxAge(30 * 24 * 3600);
            response.addCookie(cookie);
        }
    }
}
